<template>
  <a-spin :spinning="isLoading">
    <page-layout>
      <a-row :gutter="[10, 10]">
        <a-col :span="24">
          <a-form ref="formRef" :model="formState.state" :rules="formRules" :label-col="labelCol"
            :wrapper-col="wrapperCol">
            <a-card>
              <footer-button :buttons="formState.buttons" />
              <a-row>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.label.stuName')" name="stuName">
                    <a-input v-model:value="formState.state.stuName" :placeholder="t('placeholder.pleaseEnter')" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.schoolName')" name="schoolName">
                    <a-input v-model:value="formState.state.schoolName" readonly :placeholder="t('placeholder.pleaseSelect')">
                      <template #addonAfter>
                        <div class="primary-color cursor-pointer" @click="openDialog('universityVisible')">{{t('button.select')}}</div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.selectyear')" name="yuarDate">
                    <a-select v-model:value="formState.state.yuarDate">
                      <a-select-option v-for="item in dictLists.data['years']" :key="item.id"
                        :value="item.value">{{item.label}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.selectquarter')" name="quarter">
                    <a-select v-model:value="formState.state.quarter">
                      <a-select-option v-for="item in dictLists.data['quarter']" :key="item.id"
                        :value="item.value">{{item.label}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.projectName')" name="projectName">
                    <a-input v-model:value="formState.state.projectName" readonly :placeholder="t('placeholder.pleaseSelect')">
                      <template #addonAfter>
                        <div class="primary-color cursor-pointer" @click="openDialog('project')">{{t('button.select')}}</div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.courseName')" name="courseName">
                    <a-input v-model:value="formState.state.courseName" readonly :placeholder="t('placeholder.pleaseSelect')">
                      <template #addonAfter>
                        <div class="primary-color cursor-pointer" @click="openDialog('course')">{{t('button.select')}}</div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.depositprice')" name="deposit">
                    <a-input v-model:value="formState.state.deposit" :placeholder="t('placeholder.pleaseEnter')" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.exchangeRate')" name="rmbRate">
                    <a-input v-model:value="formState.state.rmbRate" :placeholder="t('placeholder.pleaseEnter')" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.fktime')" name="payTime">
                    <a-date-picker style="width:100%" v-model:value="formState.state.payTime" format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD" :placeholder="t('placeholder.selectDate')" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.fktype')" name="payChn">
                    <a-select v-model:value="formState.state.payChn">
                      <a-select-option v-for="item in dictLists.data['pay_type']" :key="item.id"
                        :value="item.value">{{item.label}}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.fknum')" name="sourceAcc">
                    <a-input v-model:value="formState.state.sourceAcc" :placeholder="t('placeholder.pleaseEnter')" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.sknum')" name="desAcc">
                    <a-input v-model:value="formState.state.desAcc" :placeholder="t('placeholder.pleaseEnter')" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.skimg')" name="payUrl">
                    <a-upload name="file" :showUploadList="false" :customRequest="(data) => handleUpload(data, 'contract')" accept=".jpg, .jpeg, .png">
                      <a-button>{{t('button.upload')}}</a-button>
                      <p
                        v-for="item in contractFiles"
                        :key="item.fileId"
                        class="mt-10"
                      >
                        {{ item.name }}
                        <DeleteOutlined
                          class="ml-10 cursor-pointer"
                          @click.prevent.stop="() => handleDelUpload('contract')"
                        />
                      </p>
                    </a-upload>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-item :label="t('deposit-manage.title.remark')" name="remark">
                    <a-input v-model:value="formState.state.remark" :placeholder="t('placeholder.pleaseEnter')" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-card>
          </a-form>
        </a-col>
      </a-row>
      <BasicTableModal v-model:visible="modalConfig.show" v-if="modalConfig.show" :columns="modalConfig.commonColumns"
        :fetchAjax="modalConfig.api" :title="modalConfig.title"
        :searchForm="modalConfig.searchForm" :searchParams="modalConfig.searchParams"
        @selectUniversity="value => selectItem(value, modalConfig.currentType , modalConfig.index)" />
    </page-layout>
  </a-spin>
</template>
<script setup>
  import {
    save,
    selectById,
    update
  } from "@/api/module/student/deposit-manage";
  import {
    onMounted,
    reactive,
    ref,
    toRaw,
    computed,
    onActivated
  } from "vue";
  import {
    useRoute,
    useRouter
  } from 'vue-router'
  import {
    getDictByCodesReturnObj
  } from '@/tools/get-dict'
  import dictEnum from '@/const/dict'
  import {
    page as schoolPage
  } from '@/api/module/school'
  import {
    page as projectPage
  } from '@/api/module/project'
  import {
    page as coursePage
  } from '@/api/module/courseBaseInfo'
  import BasicTableModal from '@/component/basic-table-modal'
  import {
    message
  } from "ant-design-vue";
  import {
    upload
  } from "@/api/module/oss"
  import moment from "moment";
  import { useI18n } from "vue-i18n";
  const  { t } = useI18n();
  let isLoading = ref(false)
  const formRef = ref();
  const route = useRoute()
  const router = useRouter()
  let modelForm = reactive({
    data: {
      files: [],
    },
  });
  const contractFiles = computed(() =>
    modelForm.data.files.filter((v) => v.type === "contract")
  );
  const handleDelUpload = (type) => {
    modelForm.data.files = modelForm.data.files.filter(
      (v) => v.type !== type
    );
  };
  const formState = reactive({
    buttons: [{
        name: 'save',
        event: () => onSubmit(),
        type: "primary",
        code: ''
      },
      {
        name: 'reset',
        event: () => resetForm(),
        code: ''
      }
    ],
    state: {
      //基础信息
      stuName: '',
      school:'',
      schoolName:'',
      yuarDate:'',
      quarter:'',
      project:'',
      projectName:'',
      course:'',
      courseName:'',
      deposit:'',
      payTime:'',
      payChn:'',
      sourceAcc:'',
      desAcc:'',
      payUrl:'',
      remark:'',
    }
  });

  const saveKey = "save";
  const labelCol = {
    span: 6
  }
  const wrapperCol = {
    span: 18
  }
  let dictLists = reactive({
    data: {},
  })
  const modalConfig = reactive({
    title: '选择学校',
    api: schoolPage,
    show: false,
    currentType: '',
    commonColumns: [],
    universityColumns: [],
    responsibleColumns: [],
    index: '',
		searchForm:[],
		schoolSearchForm:[{ label: t('deposit-manage.openDialog.chnName'), key: 'schoolCnName', type: 'input', placeholder: t('placeholder.pleaseEnter')}],
		projectSearchForm:[{ label: t('deposit-manage.openDialog.schName'), key: 'schName', type: 'input', placeholder: t('placeholder.pleaseEnter')}],
		courseSearchForm:[{ label: t('deposit-manage.openDialog.courseName'), key: 'courseName', type: 'input', placeholder: t('placeholder.pleaseEnter')}],
  })
  const formRules = {
    stuName: [{
      required: true,
      message: t('placeholder.pleaseEnter'),
      trigger: 'blur'
    }]
  };
  const getDetails = () =>{
    formRef.value.resetFields()
    if (route.query.id) {
      selectById({
        id: route.query.id
      }).then(res => {
        if (res.code === 200) {
          res.data.payTime = moment(res.data.payTime).format('YYYY-MM-DD')
          formState.state = {
            ...formState.state,
            ...res.data
          }
        }
        if (res.code === 500) return message.error(res.msg || '服务器错误')
      })
    }
  }
  onActivated(() => {
    getDetails();
    modelForm.data = {
      files: [],
    };
  });
  onMounted(async () => {
    dictLists.data = await getDictByCodesReturnObj([
      dictEnum.YEARS,
      dictEnum.QUARTER,
      dictEnum.PAY_TYPE,
    ])
    modalConfig.universityColumns = [
      {
        dataIndex: "code",
        key: "code",
        title: "学校编码"
      },
      {
        dataIndex: "schoolEnName",
        key: "schoolEnName",
        title: t('deposit-manage.openDialog.schoolEnName')
      },
      {
        dataIndex: "schFollowUpProgress",
        key: "schFollowUpProgress",
        title: t('deposit-manage.openDialog.schFollowUpProgress'),
        cellRender: (record, data) => {
          if (dictLists.data[dictEnum.FOLLOW_PROGRESS]) {
            const item = dictLists.data[dictEnum.FOLLOW_PROGRESS].find(v => v.value ==
              data)
            return item ? item.label : ''
          }
          return ''
        }
      },
    ]
    modalConfig.projectColumns = [{
        dataIndex: "schName",
        key: "schName",
        title: t('deposit-manage.openDialog.schName')
      },
      {
        dataIndex: "projectName",
        key: "projectName",
        title: t('deposit-manage.openDialog.projectName')
      },
    ]
    modalConfig.courseColumns = [{
        dataIndex: "courseCode",
        key: "courseCode",
        title: t('deposit-manage.openDialog.courseCode')
      },
      {
        dataIndex: "courseName",
        key: "courseName",
        title: t('deposit-manage.openDialog.courseName')
      },
      {
        dataIndex: "projectName",
        key: "projectName",
       title: t('deposit-manage.openDialog.projectName')
      },
      {
        dataIndex: "semester",
        key: "semester",
        title: t('deposit-manage.openDialog.semester')
      },
      {
        dataIndex: "credit",
        key: "credit",
        title: t('deposit-manage.openDialog.credit')
      },
    ]
  })
  const resetForm = () => {
    formRef.value.resetFields()
  }
  const onSubmit = () => {
      const result = formState.state;
      formRef.value.validate().then(() => {
        if (route.query.id) {
          updateItem(result)
        } else {
          saveItem(result)
        }
      })
  };
  const saveItem = (data) => {
    save(data).then(res => {
      console.log(res)
      if (res.code === 200) {
        message.success(res.message)
        router.push('/studentrtv/deposit-manage')
      }
      if (res.code === 500) return message.error(res.msg || '新增失败，服务器错误')
      isLoading = false
    }).catch(() => isLoading = false)
  }

  const updateItem = (data) => {
    update(data).then(res => {
      console.log(res)
      if (res.code === 200) {
        message.success(res.message)
        router.push('/studentrtv/deposit-manage')
      }
      if (res.code === 500) return message.error(res.msg || '编辑失败，服务器错误')
      isLoading = false
    }).catch(() => isLoading = false)
  }
  const openDialog = (type) => {
    if (type) {
      modalConfig.currentType = type
      modalConfig.show = true
      if (type === 'universityVisible') {
        modalConfig.commonColumns = modalConfig.universityColumns
        modalConfig.api = schoolPage
        modalConfig.title = t('deposit-manage.openDialog.selectschool')
		modalConfig.searchForm=modalConfig.schoolSearchForm
      } else if (type === 'project') {
		if(formState.state.schoolName!=''){
			modalConfig.commonColumns = modalConfig.projectColumns
			modalConfig.api = projectPage
			modalConfig.title = t('deposit-manage.openDialog.selectproject')
			modalConfig.searchForm=modalConfig.projectSearchForm
			modalConfig.searchParams = {'schName':formState.state.schoolName}
		}else{
			modalConfig.show = false
			message.error({
				content: '请先选择意向学校'
			})
		}
      } else if (type === 'course') {
			modalConfig.commonColumns = modalConfig.courseColumns
			modalConfig.api = coursePage
			modalConfig.title = t('deposit-manage.openDialog.selectcourse')
			modalConfig.searchForm=modalConfig.courseSearchForm
      }
    }
  }
  const closeDialog = () => {
	modalConfig.show = false
  }
  const selectItem = (value, type, index) => {
    console.log(value)
    if (type === 'universityVisible') {
		formState.state.schoolName = value.schoolEnName;
		formState.state.school = value.id;
		formState.state.projectName='';
		formState.state.project='';
    } else if (type === 'project') {
		formState.state.projectName = value.projectName;
		formState.state.project = value.id;
    } else if (type === 'course') {
		formState.state.courseName = value.courseName;
		formState.state.course = value.id;
    }
  }
  //上传文件
  const handleUpload = (data, type) => {
    const formData = new FormData()
    formData.append('file', data.file)
    upload(formData).then(res => {
      console.log(res)
      if (res.code === 500) {
        message.error({
          content: '上传附件失败'
        })
        data.onError()
      } else {
        const { path: url, id: fileId, remark, name } = res.data;
		modelForm.data.files=[];
        modelForm.data.files.push({type, url, fileId, remark, name });
        data.onSuccess(res.data)
        formState.state.payUrl = res.data.path;
      }
    })
  }
</script>
<style scoped>
  .pre-title {
    padding: 10px 25px;
    background-color: #f5f5f5;
    color: #555;
  }
</style>
